﻿Imports System.Drawing.Text
Imports System.Dynamic
Imports System.IO
Imports System.Text.RegularExpressions
Imports 报名.My.Resources

Public Class Form1
    Private WithEvents mgr As New ProcessManager()
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim file = FileVersionInfo.GetVersionInfo(System.Windows.Forms.Application.ExecutablePath)
        Me.Text = Me.Text & "." & file.FileVersion
    End Sub


    Private Sub btnFun1_Click(sender As Object, e As EventArgs)
        ' 配置进程管理器
        mgr.OutputDirectory = Path.Combine(Path.GetDirectoryName(Environment.ProcessPath), "exp", Date.Now.ToString("yyyy-MM-dd HH_mm_ss")) ' 输出目录
        mgr.MaxProcesses = CInt(numMaxProcesses.Value) ' 设置最大并发进程数
        mgr._ChildProcessName = "fun1.exe"
        ' 获取所有Excel文件
        Try
            Dim excelFiles = pickFile(myType:="EX", isMulit:=True).ToList

            mgr.AddTasks(excelFiles) ' ' 添加任务到队列

            ProgressBar.Value = 0 ' ' 重置进度条
            ProgressBar.Minimum = 0
            ProgressBar.Maximum = 100
            txtLog.Clear() ' ' 清空日志文本框
            mgr.StartProcessing() ' 传递要拆分的列名
        Catch ex As Exception
            MessageBox.Show($"没有选择文件{vbCrLf}{ex.Message}")
            Return
        End Try

    End Sub


    Private Sub btnFun2_Click(sender As Object, e As EventArgs) Handles btnFun2.Click



        Dim MbName = Path.Combine(Path.GetDirectoryName(Environment.ProcessPath), "mb.xlsx")
        If File.Exists(MbName) = False Then
            Try
                ' 从资源文件读取字节数据（资源键名为"mb"）
                Dim resourceData As Byte() = Resource.mb ' 或使用ResourceManager

                ' 将字节数据写入目标路径
                File.WriteAllBytes(MbName, resourceData)
                txtLog.AppendText($"模板文件已从资源创建：{MbName}{vbLf}")
            Catch ex As Exception
                Dim errTxt = $"资源读取失败：{ex.Message}"
                MessageBox.Show(errTxt)
                txtLog.AppendText(errTxt)
                Return
            End Try
        End If


        ' 获取所有Excel文件
        Try
            Dim excelFiles = pickFile(myType:="EX", isMulit:=True).ToList()

            ' 配置进程管理器
            mgr.OutputDirectory = Path.Combine(Path.GetDirectoryName(Environment.ProcessPath), "exp", Date.Now.ToString("yyyy-MM-dd HH_mm_ss")) ' 输出目录
            mgr.MaxProcesses = CInt(numMaxProcesses.Value) ' 设置最大并发进程数
            mgr._ChildProcessName = "fun3_20251028.exe"
            mgr.MbName = MbName

            mgr.AddTasks(excelFiles) ' ' 添加任务到队列

            ProgressBar.Value = 0 ' ' 重置进度条
            ProgressBar.Minimum = 0
            ProgressBar.Maximum = 100
            txtLog.Clear() ' ' 清空日志文本框
            mgr.StartProcessing() ' 传递要拆分的列名
        Catch ex As Exception
            MessageBox.Show($"没有选择文件{vbCrLf}{ex.Message}")
            Return
        End Try


    End Sub

    ' 事件处理：更新UI
    Private Sub OnProgressChanged(percent As Integer) Handles mgr.ProgressChanged

        ' 检查当前线程是否需要切换
        If InvokeRequired Then
            ' 通过委托异步更新（不阻塞后台线程）
            ProgressBar.BeginInvoke(Sub()
                                        ProgressBar.Value = percent
                                    End Sub)

        Else
            '当前已在 UI 线程， 直接更新控件
            ProgressBar.Value = percent
        End If
    End Sub

    Private Sub OnLogMessage(message As String) Handles mgr.LogMessage
        ' 检查当前是否在UI线程
        If txtLog.InvokeRequired Then
            ' 通过委托切换到UI线程
            txtLog.BeginInvoke(Sub()
                                   txtLog.AppendText($"{DateTime.Now}: {message}{vbCrLf}")
                               End Sub)
        Else
            ' 当前已在UI线程，直接操作
            txtLog.AppendText($"{DateTime.Now}: {message}{vbCrLf}")
        End If
    End Sub

    Private Sub OnTaskCompleted() Handles mgr.TaskCompleted
        Process.Start("explorer.exe", mgr.OutputDirectory)
        MessageBox.Show($"处理完成! ")
    End Sub

    Function pickFile(Optional ByVal myType As String = "EX" _
                     , Optional ElseStrF As String = "" _
                     , Optional isMulit As Boolean = False
                     ) As String()

        Dim FileDialog As New System.Windows.Forms.OpenFileDialog
        Dim fname() As String = Nothing
        Dim strFilt As String = ""

        With FileDialog

            Select Case UCase(myType)
                Case "EX"
                    strFilt &= "Excel(*.xls;*.xlsx)|*.xls;*.xlsx" & "|"
                Case "TXT"
                    strFilt &= "Txt files(*.txt;*.csv)|*.txt;*.csv" & "|"
                Case Else
                    If Not String.IsNullOrEmpty(ElseStrF) Then
                        strFilt &= ElseStrF & "|"
                    End If
            End Select


            strFilt &= "All Files(*.*)|*.*"

            .Filter = strFilt
            '多选
            .Multiselect = isMulit
            .SupportMultiDottedExtensions = True

            If .ShowDialog() = DialogResult.OK Then
                fname = .FileNames
            End If
        End With

        pickFile = fname
    End Function


End Class
